# -*- coding: utf-8 -*-

# -------------------------------
# Author    : linlingwei
# Email     : 951035650@qq.com
# File Name : fEye.py
# Date      : 2019/9/5 
# IDE       : PyCharm
# Version   : 1.0.1
# -------------------------------
# 20190906 : beta 0.0.1
# 20190917 : beta 0.0.2
# 20191227 : v1.1.2
import traceback
import maya.cmds as mc
import maya.mel as mel

import configs.constants.facial_constant as fc
import configs.constants.global_constant as gc
import configs.constants.suffix_constant as sc
import configs.constants.nodeType_constant as ntc
import configs.constants.attribute_constant as ac

import scripts.commonCmds as con
reload(con)
import scripts.curveCmds as cr
import scripts.deformerCmds as dc
reload(dc)
import rig.facial.fCore as fCore
reload(fCore)

class Eye(fCore.FacialCore):
    def __init__(self):
        super(Eye,self).__init__(fc.eye)
        self.transform_init()
    
    def center_point(self,prefix=""):
        center_jl = con.lname(prefix,"tmp_eyeball_center")
        sv = self.scale_value(prefix)
        trans = con.objToType(center_jl,mode=2,name=con.lname(prefix,fc.eye,fc.cr,"trans"))
        jot = mc.createNode(ntc.tJoint,name=con.lname(prefix,fc.eye,fc.cr,sc.sJot),parent=trans)
        mc.setAttr(trans+".s",sv,sv,sv)
        # mc.setAttr(jot + ".radius", 1)
        grp = con.emptyGroup(trans,["Zero"])[0]
        if prefix == fc.lf:
            con.localMirror(grp)
        mc.parent(grp,self.local_static)
        mc.sets(jot,include=self.local_sets)
        return
    def lid_setting(self):
        
        for lr in [fc.lf,fc.rt]:
            # self.center_point(lr)
            eyeball_ctr = self.eyeball_control(lr)
            
            for ul in [fc.up,fc.lo]:
                self.base_open_driver(lr,ul)
                self.lid_control(lr,ul)
                self.second_control(lr,ul)
            self.side_control(lr)
        return
    
    def base_open_driver(self,prefix=fc.lf,tag = fc.up):
        
        lname = con.lname(prefix,fc.eyelid,tag)
        lgrp = mc.createNode(ntc.tTransform,name=con.lname(lname,sc.sGrp),parent=self.local_static)
        
        center_jl = con.lname(prefix,"tmp_eyeball_center")
        mid_jl = con.lname(prefix,"tmp_Eyelid_mider_aim")
        inn_jl = con.lname(prefix,"tmp",fc.eyelid,fc.inn)
        out_jl = con.lname(prefix,"tmp",fc.eyelid,fc.out)
        loc_list = []
        locgrp_list = []
        for jl,_tag in zip([inn_jl,mid_jl,out_jl],[fc.inn,fc.mid,fc.out]):
            loc = mc.spaceLocator(name = con.lname(lname,_tag))[0]
            loc_list.append(loc)
            mc.parent(loc,lgrp)
            mc.delete(mc.pointConstraint(jl,loc,mo=False))
            _lg = con.emptyGroup(loc,["Zero"])[0]
            locgrp_list.append(_lg)
            mc.hide(loc)
        mtpca = mc.createNode(ntc.tMakeThreePointCircularArc,name=con.lname(lname,sc.sMtpca))
        for i in range(3):
            mc.connectAttr(loc_list[i]+".wp",mtpca+".pt%s"%(i+1))
        crv = mc.rename(mc.curve(p=[0,0,0],d=1,),con.lname(lname,"openBase",sc.sCrv))
        mc.connectAttr(mtpca+".oc",con.findRelatedShape(crv)+".create")
        crv_offset = con.objToType(con.lname(prefix,"tmp",fc.eyelid,fc.cr,"crv_offset"),
                                   name = con.lname(crv,ac.offset))
        mc.parent(crv_offset,self.local_static)
        crv_offsetGrp = con.emptyGroup(crv_offset,["Zero"])[0]
        mc.parent(crv,crv_offset)
        mc.hide(crv_offsetGrp)
        crvgrp = con.emptyGroup(crv,["Zero"])[0]
        mc.setAttr(crv_offset+".ty",mc.getAttr(con.lname(prefix,"tmp",fc.eyelid,tag,"crv_offset")+".ty"))
        
        c_tansform = mc.createNode(ntc.tTransform,name=con.lname(lname,"centerRot"))
        mc.delete(mc.pointConstraint(center_jl,c_tansform,mo=False))
        mc.delete(mc.orientConstraint(con.lname(prefix,"tmp_Eyelid_Up_rot_Zero"),c_tansform,mo=False))
        c_tansformGrp = con.emptyGroup(c_tansform,["Zero"])[0]
        mc.parent(locgrp_list[1],c_tansform)
        mc.parent(crv_offsetGrp,c_tansformGrp,lgrp)

        _attr = con.lname(prefix,fc.eyelid,tag,fc.op)
        mc.addAttr(lgrp,ln=_attr,at="float",dv=0,k=True)
        
        mc.hide(c_tansformGrp)
        
        self.lid_open_sdk(prefix,tag)
        
        sdk_crv = mc.duplicate(crv, name=con.lname(lname, "SDK"))[0]
        sdk_bls = mc.blendShape(crv,sdk_crv,w=[0,1],name = con.lname(lname, "SDK",sc.sBls))[0]
        
        crv_list = list()
        for kw in [fc.op+"Tgt",fc.cl+"Tgt","rot"]:
            _crv = mc.duplicate(crv,name = con.lname(lname,kw))[0]
            crv_list.append(_crv)
            dc.blendShapeAppendTgt(sdk_bls,_crv)

        mc.setDrivenKeyframe(con.lAttr(sdk_bls,crv_list[0]),
                             cd=con.lAttr(lgrp,_attr), dv=0, v=0, itt="linear", ott="linear")
        mc.setDrivenKeyframe(con.lAttr(sdk_bls,crv_list[0]),
                             cd=con.lAttr(lgrp,_attr), dv=10, v=1, itt="linear", ott="linear")
        
        mc.setDrivenKeyframe(con.lAttr(sdk_bls,crv_list[1]),
                             cd=con.lAttr(lgrp,_attr), dv=0, v=0, itt="linear", ott="linear")
        mc.setDrivenKeyframe(con.lAttr(sdk_bls,crv_list[1]),
                             cd=con.lAttr(lgrp,_attr), dv=-10, v=1, itt="linear", ott="linear")
        mc.setAttr(con.lAttr(sdk_bls,crv_list[2]),1)
        
        output_crv = mc.duplicate(crv, name=con.lname(lname, "output"))[0]
        lid_skin_jot = self.lid_skin_jot(prefix,tag,output_crv)
        lid_rot = self.lid_rot(prefix,tag,crv_list[2])
        con.transferAttr(lid_rot,lgrp,(con.lname(prefix,fc.eyelid,tag,"rot","ry"),
                                       con.lname(prefix,fc.eyelid,tag,"rot","rz")))
        for _t in [fc.inn,fc.out]:
            con.transferAttr(lid_rot, lgrp, (con.lname(prefix, fc.eyelid, _t, fc.ul),
                                             con.lname(prefix, fc.eyelid, _t, fc.lr)))

        mc.parent(lid_skin_jot,lid_rot,lgrp)
        
        sdwire = self.second_driver(prefix,tag,sdk_crv)
        mc.blendShape(sdk_crv,sdwire,output_crv,w=[(0,1),(1,1)],name=con.lname(lname,"output",sc.sBls))
        
        con.transferAttr(lgrp,self.local_static,(_attr,
                                                 con.lname(prefix,fc.eyelid,tag,"rot",'ry'),
                                                 con.lname(prefix,fc.eyelid,tag,"rot",'rz'),))
        for _t in [fc.inn,fc.out]:
            con.transferAttr(lgrp, self.local_static, (con.lname(prefix, fc.eyelid, _t, fc.ul),
                                             con.lname(prefix, fc.eyelid, _t, fc.lr)))
        return
    
    def lid_open_sdk(self,prefix=fc.lf,tag = fc.up):

        lname = con.lname(prefix, fc.eyelid, tag)
        tmp_lname = con.lname(prefix,"tmp",fc.eyelid,)

        if tag == fc.up:
            openTmp = -mc.getAttr(con.lAttr(con.lname(tmp_lname,fc.up,"openMax",sc.sCrv,),"openMax"))
            closeTmp = mc.getAttr(con.lAttr(con.lname(tmp_lname,fc.lo,"openMax",sc.sCrv,),"openMax"))
        else:
            openTmp = mc.getAttr(con.lAttr(con.lname(tmp_lname,fc.lo,"openMax",sc.sCrv,),"openMax"))
            closeTmp = -mc.getAttr(con.lAttr(con.lname(tmp_lname,fc.up,"openMax",sc.sCrv,),"openMax"))
        
        dr = con.lAttr(con.lname(lname,sc.sGrp),con.lname(prefix,fc.eyelid,tag,fc.op))
        dn_obj = con.lname(lname,"centerRot")
        dn = con.lAttr(dn_obj,"rx")
        mc.setDrivenKeyframe(dn, cd=dr, dv=0, v=0, itt="linear", ott="linear")
        if prefix == fc.lf:
            mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=closeTmp, itt="spline", ott="spline")
            mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=openTmp, itt="spline", ott="spline")

        else:
            mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=-closeTmp, itt="spline", ott="spline")
            mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=-openTmp, itt="spline", ott="spline")

        mc.setAttr(con.lname(dn_obj,"rotateX") + ".postInfinity", 1)
        mc.setAttr(con.lname(dn_obj,"rotateX") + ".preInfinity", 1)
        
        # # ---
        # if tag == fc.up:
        #     openTmp = mc.getAttr(con.lAttr(con.lname(tmp_lname, fc.up+fc.mid,"aim_Zero" ), "tz"))
        #     closeTmp = mc.getAttr(con.lAttr(con.lname(tmp_lname,  fc.lo+fc.mid,"aim_Zero", ), "tz"))
        # else:
        #     openTmp = mc.getAttr(con.lAttr(con.lname(tmp_lname,  fc.lo+fc.mid,"aim_Zero", ), "tz"))
        #     closeTmp = mc.getAttr(con.lAttr(con.lname(tmp_lname,  fc.up+fc.mid,"aim_Zero", ), "tz"))
        #
        # dr = con.lAttr(con.lname(lname, sc.sGrp), con.lname(prefix, fc.eyelid, tag, fc.op))
        # dn_obj = con.lname(lname, "mider_Zero")
        # dn = con.lAttr(dn_obj, "tz")
        # dn_dv = mc.getAttr(dn)
        # mc.setDrivenKeyframe(dn, cd=dr, dv=0, v=dn_dv, itt="linear", ott="linear")
        # mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=openTmp, itt="linear", ott="linear")
        # mc.setDrivenKeyframe(dn, cd=dr, dv=12, v=openTmp*1.05, itt="spline", ott="spline")
        # mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=closeTmp, itt="linear", ott="linear")
        # mc.setDrivenKeyframe(dn, cd=dr, dv=-12, v=closeTmp*1.05, itt="spline", ott="spline")
        #
        # mc.setAttr(con.lname(dn_obj, "translateZ") + ".postInfinity", 1)
        # mc.setAttr(con.lname(dn_obj, "translateZ") + ".preInfinity", 1)

        return
    
    def lid_skin_jot(self,prefix=fc.lf,tag = fc.up,crv=None):
        
        lname = con.lname(prefix,fc.eyelid,tag,"skin")
        output_crv = crv
        output_crvShape = con.findRelatedShape(output_crv)
        tmp_root = prefix+"_tmp_eyeball_center"
        # crv_max = mc.getAttr(output_crvShape+".maxValue")
        lgrp = mc.createNode(ntc.tTransform,name=con.lname(lname,sc.sGrp))

        pgrp = mc.createNode(ntc.tTransform,name=con.lname(lname,"point",sc.sGrp),parent=lgrp)
        jgrp = mc.createNode(ntc.tTransform,name=con.lname(lname,"skin",sc.sGrp),parent=lgrp)
        mc.delete(mc.pointConstraint(tmp_root,jgrp,mo=False))
        sk_jot = mc.ls(prefix+"_tmp_Eyelid_Lo_skin*_loc",fl=True)
        jot_list = list()
        for i,sj in enumerate(sk_jot[1:-1]):
            par = con.getObjInCrvParameter(output_crv,sj)
            poci = mc.createNode(ntc.tPointOnCurveInfo,name=con.lname(lname,i,sc.sPoci))
            mc.connectAttr(output_crvShape+".ws",poci+".ic")
            # mc.setAttr(poci+".top",1)
            mc.setAttr(poci+".pr",par)
            
            trans = mc.createNode(ntc.tTransform,name=con.lname(lname,i,"point"))
            mc.connectAttr(poci+".p",trans+".t")
            mc.parent(trans,pgrp)
            
            # rjot = mc.createNode(ntc.tJoint,name =con.lname(lname,i,"root",sc.sJot))
            rjot = con.objToType(tmp_root,name=con.lname(lname,i,"root",sc.sJot),typ=ntc.tJoint)
            ajot = con.objToType(trans,name=con.lname(lname,i,"end",sc.sJot),typ=ntc.tJoint)
            jot_list.append(ajot)
            mc.parent(ajot,rjot)
            con.jointOrient([rjot,ajot])
            ikh = mc.ikHandle(sj=rjot,ee=ajot,name=con.lname(lname,i,"skin",sc.sIkhandle),sol="ikSCsolver")[0]
            mc.hide(ikh)
            mc.parent(ikh,trans)
            mc.parent(rjot,jgrp)
            
            # mc.setAttr(rjot+".radius",0.1)
            # mc.setAttr(ajot+".radius",0.1)
            
            dis = mc.createNode(ntc.tDistanceBetween,name=con.lname(lname,i,sc.sDbn))
            mc.connectAttr(jgrp+".m",dis+".im1")
            mc.connectAttr(trans+".m",dis+'.im2')
            mc.connectAttr(dis+".d",ajot+".tx")
            
            mc.setAttr(ajot+".jointOrient",0,0,0)
            sjot = mc.createNode(ntc.tJoint,name=con.lname(lname,i,"skin",sc.sJot),parent=ajot)
            con.hideJoint(rjot,ajot)
            mc.setAttr(sjot+".radius",0.1)

            # --- 2019/10/21 update
            mc.addAttr(sjot,ln=ac.offset,at="float",dv=par,k=True,min=0)
            mc.connectAttr(con.lAttr(sjot,ac.offset),poci+".pr")

        # mc.parent(pgrp,jgrp,self.local_static)
        mc.sets(jot_list,include=self.local_sets)
        return lgrp
    
    def lid_rot(self,prefix=fc.lf,tag = fc.up,crv = None):
        center_jl = con.lname(prefix,"tmp_eyeball_center")
        mid_jl = con.lname(prefix,"tmp_Eyelid_mider_aim")
        inn_jl = con.lname(prefix,"tmp",fc.eyelid,fc.inn)
        out_jl = con.lname(prefix,"tmp",fc.eyelid,fc.out)
        
        sv = self.scale_value(prefix)
        
        lname = con.lname(prefix,fc.eyelid,tag,"rot")
        lgrp = mc.createNode(ntc.tTransform,name = con.lname(prefix,fc.eyelid,tag,"rot",sc.sGrp),
                             parent=self.local_static)
        # mc.hide(lgrp)
        jot_list = list()
        ikh_list = list()
        for jl,_t in zip([inn_jl,out_jl],[fc.inn,fc.out]):
            inroot_jot = con.objToType(center_jl,name=con.lname(lname,_t,"root",sc.sJot),typ=ntc.tJoint,mode=0)
            inn_jot =con.objToType(jl,name=con.lname(lname,_t,sc.sJot),typ=ntc.tJoint,mode=0)
            mc.parent(inn_jot,inroot_jot)
            con.jointOrient([inroot_jot,inn_jot])
            
            # mc.setAttr(inroot_jot+".radius",0.05)
            # mc.setAttr(inn_jot+".radius",0.05)
            mc.setAttr(inn_jot+".jointOrient",0,0,0)

            ikh = mc.ikHandle(sj=inroot_jot,ee=inn_jot,sol="ikSCsolver",name=con.lname(inn_jot,sc.sIkhandle))[0]
            mc.hide(ikh)
            jot_list.append(inn_jot)
            ikh_list.append(ikh)
            
            # trans = con.objToType(jl,name = con.lname(lname,_t,"trans"))
            trans = mc.createNode(ntc.tTransform,name = con.lname(lname,_t,"trans"))
            mc.delete(mc.pointConstraint(jl,trans,mo=False))
            mc.setAttr(trans+".s",sv,sv,sv)
            # mc.delete(mc.orientConstraint(inn_jl,trans,mo=False))
            mc.parent(trans,lgrp)
            con.emptyGroup(trans,["Zero"])
            mc.parent(ikh,trans)
            
            mc.parent(inroot_jot,lgrp)
            
            _attr = con.lname(prefix,fc.eyelid,_t,fc.ul)
            if not mc.attributeQuery(_attr,node=lgrp,ex=True):
                mc.addAttr(lgrp,ln=_attr,at="float",dv=0,k=True)
            mc.connectAttr(con.lAttr(lgrp,_attr),trans+".ty")
            _attr = con.lname(prefix,fc.eyelid,_t,fc.lr)
            if not mc.attributeQuery(_attr,node=lgrp,ex=True):
                mc.addAttr(lgrp,ln=_attr,at="float",dv=0,k=True)
            mc.connectAttr(con.lAttr(lgrp,_attr),trans+".tx")
            
            con.hideJoint(inroot_jot,inn_jot)
            if tag == fc.up:
                sjot = mc.createNode(ntc.tJoint, name=con.lname(lname,_t,"skin",sc.sJot), parent=inn_jot)
                mc.parent(sjot,inroot_jot)
                mc.setAttr(sjot + ".radius", 0.1)
                con.emptyGroup(sjot,["Zero"])
        # L_tmp_Eyelid_Up_rot_Zero
        tmp = con.lname(prefix,"tmp",fc.eyelid,tag,"rot_Zero")
        rot_trans = con.objToType(tmp,name=con.lname(lname,fc.mid,"trans"),mode=2)
        rog_grp = con.emptyGroup(rot_trans,["Zero","ry","rz"])[0]
        mc.parent(rog_grp,lgrp)
        # jot_list.append(rot_jot)
        rot_jot = mc.createNode(ntc.tJoint,name=con.lname(lname,fc.mid,sc.sJot),parent=rot_trans)
        mc.hide(rot_jot)
        skin = mc.skinCluster(jot_list+[rot_jot],crv,name= con.lname(lname,ntc.tSkinCluster),mi=2,rui=False)[0]
        
        cvs = mc.ls(crv+".cv[*]",fl=True)
        cvsNumber = (len(cvs)-1)/2
        wv = [0,0.2,0.55,0.75,0.9]
        for i,cv in enumerate(cvs):
            # print i
            if i<cvsNumber:
                v = wv[i]
                mc.skinPercent(skin,cv,transformValue=[(jot_list[0],1-wv[i]),(jot_list[1],0),(rot_jot,wv[i])])
            elif i == cvsNumber:
                v = 1
                mc.skinPercent(skin, cv, transformValue=[(jot_list[0], 0), (jot_list[1], 0), (rot_jot, 1)])
            elif i>cvsNumber:
                v = wv[cvsNumber-i]
                mc.skinPercent(skin, cv, transformValue=[(jot_list[0], 0), (jot_list[1],1- wv[cvsNumber-i]), (rot_jot, wv[cvsNumber-i])])
            # print i,v
        
        for _at in ["ry","rz"]:
            at_name =con.lname(lname,_at)
            mc.addAttr(lgrp,ln=at_name,at="float",dv=0,k=True)
    
            mdl = mc.createNode(ntc.tMultDoubleLinear,name = con.lname(at_name,sc.sMdl))
            mc.connectAttr(con.lAttr(lgrp,at_name),mdl+".i1")
            if prefix == fc.lf:
                mc.setAttr(mdl+".i2",1,l=True)
            else:
                mc.setAttr(mdl+".i2",-1,l=True)
    
            mc.connectAttr(mdl+".o",rot_trans+"."+_at)

        return lgrp
    
    def second_driver(self,prefix=fc.lf,tag = fc.up,crv = None):
        
        lname = con.lname(prefix,fc.eyelid,tag,"SD")
        lgrp = mc.createNode(ntc.tTransform,name = con.lname(lname,sc.sGrp),parent = self.local_static)
        mc.hide(lgrp)
        crvShape = con.findRelatedShape(crv)
        
        sv = self.scale_value(prefix)

        #L_Eyelid_Cr_ctrl_2_loc
        center_jl = con.lname(prefix,"tmp_eyeball_center")
        secPts = mc.ls(con.lname(prefix,fc.eyelid,fc.cr,"ctrl*_loc"),fl=True)
        pt_list = [mc.xform(_,q=True,ws=True,t=True) for _ in secPts]
        wire_crv = mc.rename(mc.curve(p=pt_list,),con.lname(lname, "Wire"))
        sdk_crv = mc.duplicate(crv, name=con.lname(lname,))[0]
        mc.parent(wire_crv,mc.listRelatives(crv,p=True)[0])
        
        loc_grp = mc.createNode(ntc.tTransform,name = con.lname(lname,sc.sLoc,sc.sGrp),parent=lgrp)
        jot_grp = mc.createNode(ntc.tTransform,name = con.lname(lname,sc.sJot,sc.sGrp),parent=lgrp)
        mc.delete(mc.pointConstraint(center_jl,jot_grp,mo=False))
        trans_grp = mc.createNode(ntc.tTransform,name = con.lname(lname,"trans",sc.sGrp),parent=lgrp)
        for i,spt in enumerate(secPts):
            par = mc.getAttr(con.lAttr(spt,ac.offset))/100.
            poci = mc.createNode(ntc.tPointOnCurveInfo,name=con.lname(lname,i,sc.sPoci))
            mc.connectAttr(crvShape+".ws",poci+".ic")
            mc.setAttr(poci+".top",1)
            mc.setAttr(poci+".pr",par)
            
            trans = mc.createNode(ntc.tTransform,name = con.lname(lname,i,"trans"),parent=trans_grp)
            mc.connectAttr(poci+".p",trans+".t")
            
            rjot = con.objToType(center_jl, name=con.lname(lname, i, "root", sc.sJot), typ=ntc.tJoint)
            jot = con.objToType(trans, name=con.lname(lname, i+1, "point",sc.sJot), typ=ntc.tJoint)
            mc.parent(jot, rjot)
            con.jointOrient([rjot, jot])
            mc.parent(rjot, jot_grp)
            
            mc.setAttr(rjot+".radius",0.05)
            mc.setAttr(jot+".radius",0.05)
            
            ikh = mc.ikHandle(sj=rjot, ee=jot, sol="ikSCsolver", name=con.lname(lname, i, sc.sIkhandle))[0]

            mc.parent(ikh,trans)
            
            dbl = mc.createNode(ntc.tDistanceBetween,name = con.lname(lname,i,sc.sDbn))
            mc.connectAttr(trans+".m",dbl+".im1")
            mc.connectAttr(jot_grp+".m",dbl+".im2")
            mc.connectAttr(dbl+".d",jot+".tx")
            
            sdloc = mc.spaceLocator(name = con.lname(lname,i+1,sc.sLoc))[0]
            mc.delete(mc.pointConstraint(trans,sdloc,mo=False))
            sdlocShape = con.findRelatedShape(sdloc)
            mc.parent(sdloc,loc_grp)
            mc.setAttr(sdloc+".s",sv,sv,sv)
            con.emptyGroup(sdloc,["Zero"])
            mc.connectAttr(sdlocShape+".wp",wire_crv+".cv[%s]"%i)
            
            mc.hide(ikh,sdloc)
            
        _wire = mc.wire(sdk_crv,w=wire_crv,name = con.lname(lname,sc.sWire),dds=[0,100*1000])[0]
        mc.setAttr(_wire+".rotation",0)
        return sdk_crv
    
    def scale_value(self,prefix):
        # if not self.sv:
        up_tmpPt_loc = con.lname(prefix, "tmp", fc.eyelid, fc.up + fc.mid, "aim")
        lo_tmpPt_loc = con.lname(prefix, "tmp", fc.eyelid, fc.lo + fc.mid, "aim")
    
        upPt = mc.xform(up_tmpPt_loc, q=True, ws=True, t=True)[1]
        loPt = mc.xform(lo_tmpPt_loc, q=True, ws=True, t=True)[1]
        sv = (upPt - ((abs(upPt) + abs(loPt)) * .5)) * .1
        return sv

    def lid_control(self,prefix=fc.lf,tag = fc.up,):
        
        center_jl = con.lname(prefix,"tmp_eyeball_center")
        mid_jl = con.lname(prefix,"tmp_Eyelid_mider_aim")
        inn_jl = con.lname(prefix,"tmp",fc.eyelid,fc.inn)
        out_jl = con.lname(prefix,"tmp",fc.eyelid,fc.out)
        
        tmpRot_loc = con.lname(prefix,"tmp",fc.eyelid,fc.mid)
        sv = self.scale_value(prefix)
        
        ctr = cr.objToControl(tmpRot_loc,name=con.lname(prefix,fc.eyelid,tag,),colorId=17,ctrlShape="semicircle")
        
        mc.setAttr(ctr+".s",sv,sv,sv)
        mc.parent(ctr,con.lname(prefix,fc.eyeball,sc.sCtr))
        ctrGrp = con.emptyGroup(ctr)
        cr.scaleXYZ(ctr, 4)
        
        _attr = con.lname(prefix,fc.eyelid,tag,fc.op)
        dr = ctr+'.ty'
        dn = con.lAttr(self.local_static,_attr)
        mc.setDrivenKeyframe(dn, cd=dr, dv=0, v=0, itt="spline", ott="spline")
        
        if tag == fc.up:
            mc.setAttr(ctrGrp[1]+".ty",0.1)
            cr.rotate(ctr,90)
            mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=10, itt="spline", ott="spline")

        else:
            mc.setAttr(ctrGrp[1]+".ty",-0.1)
            cr.rotate(ctr,-90)
            mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=10, itt="spline", ott="spline")

        # _attr = con.lname(prefix,fc.eyelid,tag,fc.op)
        # mc.connectAttr(ctr+'.ty',con.lAttr(self.local_static,_attr))
        
        # if prefix == fc.lf:
        #     mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=10, itt="spline", ott="spline")
        # else:
        #     mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=10, itt="spline", ott="spline")

        mc.setAttr(con.lname(self.local_static,_attr) + ".postInfinity", 1)
        mc.setAttr(con.lname(self.local_static,_attr) + ".preInfinity", 1)
        
        _attr = con.lname(prefix,fc.eyelid,tag,"rot","rz")
        mc.connectAttr(ctr+'.rz',con.lAttr(self.local_static,_attr))
        
        
        ox,oy,oz = mc.xform(center_jl,q=True,ws=True,t=True)
        ix1, iy1, iz1 = mc.xform(inn_jl, q=True, ws=True, t=True)
        ix2, iy2, iz2 = mc.xform(out_jl, q=True, ws=True, t=True)
        # print [ix1-ox,iy1-oy,iz1-oz],[ix2-ox,iy2-oy,iz2-oz]
        an = con.angle([ix1-ox,iy1-oy,iz1-oz],[ix2-ox,iy2-oy,iz2-oz])
        dr = ctr+'.tx'
        _attr = con.lname(prefix,fc.eyelid,tag,"rot","ry")
        dn = con.lAttr(self.local_static,_attr)
        mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=an*.5, itt="linear", ott="linear")
        mc.setDrivenKeyframe(dn, cd=dr, dv=0, v=0, itt="linear", ott="linear")
        mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=-an*.5, itt="linear", ott="linear")
        mc.setAttr(con.lname(self.local_static,_attr) + ".postInfinity", 1)
        mc.setAttr(con.lname(self.local_static,_attr) + ".preInfinity", 1)

        return
    
    def second_control(self,prefix=fc.lf,tag = fc.up):
        
        cnt_loc = mc.ls(con.lname(prefix,fc.eyelid,tag,"SD_*_"+sc.sLoc))
        pt_jot = mc.ls(con.lname(prefix,fc.eyelid,tag,"SD_*_point_"+sc.sJot))
        sv = self.scale_value(prefix)
        
        lgrp = mc.createNode(ntc.tTransform,name = con.lname(prefix,fc.eyelid,tag,"SDC",sc.sGrp))
        ctr_list = []
        for i,cl,pj in zip(range(len(cnt_loc)),cnt_loc,pt_jot):
            # print i,cl,pj
            ctr = cr.objToControl(cl,name = con.lname(prefix,fc.eyelid,tag,i+1),colorId=20)
            mc.setAttr(ctr + ".s", sv, sv, sv)
            mc.parent(ctr,lgrp)
            ctrGrp = con.emptyGroup(ctr)
            
            dm = mc.createNode("decomposeMatrix",name = con.lname(prefix,fc.eyelid,tag,i+1,"DM"))
            mc.connectAttr(pj+".wm",dm+".inputMatrix")
            mc.connectAttr(dm+".outputTranslate",ctrGrp[0]+".t")
            
            mc.connectAttr(ctr+".t",cl+".t")
            cl_g = con.emptyGroup(cl,["cnt"])[0]
            mc.connectAttr(ctrGrp[2]+".t",cl_g+".t")
            
            con.lockHideAttr(ctr,ignore=["tx","ty","tz"])
            cr.rotate(ctr,90)
            ctr_list.append(ctr)
        if len(ctr_list ) == 9:
            for i,index in enumerate([1,4,7],1):
                ctr_z = con.lname(ctr_list[index],"Zero")
                mctr = cr.objToControl(ctr_z,name=con.lname(prefix,fc.eyelid,tag,"master%s"%i),colorId=18,ctrlShape="cube")
                mc.setAttr(mctr + ".s", sv, sv, sv)
                mc.parent(mctr,ctr_z)
                mctr_g = con.emptyGroup(mctr)
                mc.connectAttr(mctr+".t",con.lname(ctr_list[index],"Sdk")+".t")
                if i == 1:
                    mc.connectAttr(mctr+".t",con.lname(ctr_list[index+1],"Sdk")+".t")
                elif i == 2:
                    mc.connectAttr(mctr+".t",con.lname(ctr_list[index-1],"Sdk")+".t")
                    mc.connectAttr(mctr+".t",con.lname(ctr_list[index+1],"Sdk")+".t")
                elif i == 3:
                    mc.connectAttr(mctr+".t",con.lname(ctr_list[index-1],"Sdk")+".t")
                con.lockHideAttr(mctr,ignore=["tx","ty","tz"])

        mc.parent(lgrp,con.lname(prefix,fc.eyeball,sc.sCtr))
        return
    
    def side_control(self,prefix=fc.lf):
        
        #L_tmp_eyelid_inn_jot
        rot_tmp = con.lname(prefix,"tmp",fc.eyelid,fc.inn,sc.sJot)
        inn_tmp = con.lname(prefix,"tmp",fc.eyelid,fc.inn)
        out_tmp = con.lname(prefix,"tmp",fc.eyelid,fc.out)
        
        sv = self.scale_value(prefix)
        
        ctr_list= list()
        for tag,jl in zip([fc.inn,fc.out],[inn_tmp,out_tmp]):
            ctr = cr.objToControl(jl,name = con.lname(prefix,fc.eyelid,tag),colorId=17,ctrlShape="triangle")
            mc.delete(mc.orientConstraint(rot_tmp,ctr,mo=False))
            mc.setAttr(ctr+".s",sv,sv,sv)
            mc.parent(ctr,con.lname(prefix,fc.eyeball,sc.sCtr))
            con.emptyGroup(ctr)
            ctr_list.append(ctr)
            con.lockHideAttr(ctr,ignore=["tx","ty","tz"])
            cr.scaleXYZ(ctr, 4)

            # _attr = con.lname(prefix,fc.eyelid,tag,fc.ul)
            # mc.connectAttr(ctr+".ty",con.lAttr(self.local_static,_attr))
            # _attr = con.lname(prefix,fc.eyelid,tag,fc.lr)
            # mc.connectAttr(ctr+".tx",con.lAttr(self.local_static,_attr))
            #
            
            
            for _a,da in zip([fc.ul,fc.lr],["ty","tx"]):
                _attr = con.lname(prefix,fc.eyelid,tag,_a)
                dr = con.lAttr(ctr,da)
                dn = con.lAttr(self.local_static,_attr)
                mc.setDrivenKeyframe(dn, cd=dr, dv=0, v=0, itt="spline", ott="spline")
                # print tag,da
                if prefix == fc.rt and da == "tx":
                    print 1
                    mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=10, itt="spline", ott="spline")
                else:
                    mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=10, itt="spline", ott="spline")
                mc.setAttr(con.lname(self.local_static, _attr) + ".postInfinity", 1)
                mc.setAttr(con.lname(self.local_static, _attr) + ".preInfinity", 1)
        return
    
    def eyeball_control(self,prefix):
        
        center_jl = con.lname(fc.lf,"tmp_eyeball_center")
        
        sv = self.scale_value(prefix)
        ctr = cr.objToControl(center_jl,name = con.lname(prefix,fc.eyeball),ctrlShape="cube",colorId=13)
        ctr_loc = mc.createNode(ntc.tTransform,name = con.lname(prefix,fc.eyeball,"trans"),parent=ctr)
        cjot = mc.createNode(ntc.tJoint,name=con.lname(prefix,fc.eyeball,sc.sJot),parent=ctr_loc)
        mc.setAttr(ctr+".s",sv,sv,sv)
        mc.parent(ctr,self.local_toParent)
        ctr_g = con.emptyGroup(ctr)
        if prefix == fc.rt:
            con.localMirror(ctr_g[0],"world")
        cr.scaleXYZ(ctr,25)
        
        ctr_loc_g = con.emptyGroup(ctr_loc)
        mc.parent(ctr_loc_g[0],self.local_static)
        for _at in ["t","r","s"]:
            mc.connectAttr(con.lAttr(ctr,_at),con.lAttr(ctr_loc,_at))
        
        con.lockHideAttr(ctr,["v"])
        
        return ctr
    def create(self):
        
        try:
            self.lid_setting()
            self.hide_doDelete()

            print " - EyeLid Rig Complete - "
        except:
            traceback.print_exc()
        
        return
    
    def eyeSocket_loc(self):

        # L_EyeSocket_tmp_Up_3_loc
        for lr in [fc.lf,fc.rt]:
            ctr_lgrp = mc.createNode(ntc.tTransform, name=con.lname(lr,fc.eyeSocket, sc.sCtr, sc.sGrp),
                                     parent=self.local_toParent)
            jot_lgrp = mc.createNode(ntc.tTransform, name=con.lname(lr,fc.eyeSocket, sc.sJot, sc.sGrp),
                                     parent=self.local_static)
            uploc = mc.ls(con.lname(lr,fc.eyeSocket,"tmp",fc.up,"*",sc.sLoc),fl=True)
            loloc = mc.ls(con.lname(lr,fc.eyeSocket,"tmp",fc.lo,"*",sc.sLoc),fl=True)[1:-1]
            
            jot_list = list()
            for locs,tag in zip([uploc,loloc],[fc.up,fc.lo]):
                for i,ls in enumerate(locs):
                    _nn = con.lname(lr,fc.eyeSocket,tag,i+1)
                    ctr = cr.objToControl(ls,name=_nn,ctrlShape="cube",colorId=18)
                    # cr.scaleXYZ(ctr,0.05)
                    jot = mc.createNode(ntc.tJoint,name = con.lname(_nn,sc.sJot),parent=ctr)
                    jot_list.append(jot)
                    # mc.setAttr(jot+".radius",0.035)
                    if lr == fc.rt:
                        con.localMirror(ctr)
                    ctr_grp = con.emptyGroup(ctr)
                    jot_grp = con.emptyGroup(jot,["Zero","Con","Sdk","Ci"])
                    for _ctr,_jot in zip(ctr_grp[2:]+[ctr],jot_grp[2:]):
                        for _at in ["t","r","s"]:
                            mc.connectAttr(con.lAttr(_ctr,_at),con.lAttr(_jot,_at))
                    mc.parent(ctr_grp[0],ctr_lgrp)
                    mc.parent(jot_grp[0],jot_lgrp)
            mc.sets(jot_list,include=self.local_sets)
        return

    def socket_create(self):
    
        try:
            self.eyeSocket_loc()
            self.hide_doDelete()
        
            print " - EyeLid Rig Complete - "
        except:
            traceback.print_exc()
    
        return
    
    def correct_point(self,up_sorg,lo_sorg):
        
        upcrv = mc.rename(up_sorg,con.lname(fc.up,sc.sCrv))
        locrv = mc.rename(lo_sorg, con.lname(fc.lo, sc.sCrv))
        # jot_tag = "L_Eyelid_Up_skin_1_skin_jot"

        jot_tag = con.lname(fc.lf, fc.eyelid, fc.up, "skin*_skin", sc.sJot)
        jotlist = mc.ls(jot_tag, fl=True)
        dvlist = list()
        uvlist = list()
        lvlist = list()
        for i, jot in enumerate(jotlist):
            dn = jot + "." + ac.offset
            v = mc.getAttr(dn)
            dvlist.append(v)

            cv = con.lname(fc.up, sc.sCrv) + ".cv[%s]" % i
            tcrv = "L_tmp_Eyelid_%s_openMax_crv" % fc.up
            uv = con.getObjInCrvParameter(tcrv, cv)
            uvlist.append(uv)

            cv = con.lname(fc.lo, sc.sCrv) + ".cv[%s]" % i
            tcrv = "L_tmp_Eyelid_%s_openMax_crv" % fc.lo
            lv = con.getObjInCrvParameter(tcrv, cv)
            lvlist.append(lv)
            # print v,uv,lv

        for lr in [fc.lf, fc.rt]:
            for ul in [fc.up,fc.lo]:
                jot_tag = con.lname(lr,fc.eyelid,ul,"skin*_skin",sc.sJot)
                jotlist = mc.ls(jot_tag,fl=True)
                for jot,dv,uv,lv in zip(jotlist,dvlist,uvlist,lvlist):
                    dr = con.lAttr("facial_Eye_Static",con.lname(lr,fc.eyelid,ul,fc.op))
                    dn = jot+"."+ac.offset
                    mc.setDrivenKeyframe(dn, cd=dr, dv=0, v=dv, itt="linear", ott="linear")
                    if ul == fc.up:
                        mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=uv, itt="linear", ott="linear")
                        mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=lv, itt="linear", ott="linear")
                    else:
                        mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=uv, itt="linear", ott="linear")
                        mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=lv, itt="linear", ott="linear")
        return
    
    def blendShape_list(self,meshObj):
        
        bls = con.lname(fc.head,"f"+sc.sGeo,ntc.tBlendShape)
        _bls = dc.findRelatedDeformer(meshObj,typ=ntc.tBlendShape)
        if not _bls:
            mc.blendShape(meshObj,foc=1,name=bls)
        else:
            mc.rename(_bls,bls)
        org_mesh = con.lname(fc.head,"f"+sc.sGeo,"org")
        for lr in [fc.lf,fc.rt]:
            for ul in [fc.up,fc.lo]:
                # -- open driver
                attr = con.lname(lr,fc.eyelid,ul,fc.op)
                if not dc.blendShapeItemExist(bls,attr):
                    tgt = mc.rename(mc.duplicate(org_mesh)[0],attr)
                    mc.parent(tgt,self.local_blsTgtgGrp)
                    dc.blendShapeAppendTgt(bls,tgt)
                dr = con.lAttr(self.local_static,attr)
                dn = con.lAttr(bls,attr)
                mc.setDrivenKeyframe(dn, cd=dr, dv=0, v=1, itt="linear", ott="linear")
                if ul == fc.up:
                    mc.setDrivenKeyframe(dn, cd=dr, dv=10, v=0, itt="linear", ott="linear")
                else:
                    mc.setDrivenKeyframe(dn, cd=dr, dv=-10, v=0, itt="linear", ott="linear")
        
        return
if __name__ == '__main__':
    pass